<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 4/14/17
 * Time: 9:57 AM
 */

namespace api\modules\bank\controllers;


use common\components\sms\Lhwt;
use common\components\tools\Tools;
use common\models\BankBackSendLog;
use common\models\CarOrderBankBackLog;
use common\models\Custom;
use common\models\ManualPics;
use common\models\ManualPicsGetLog;
use common\models\MultiMedia;
use common\models\SpecialCardBankBackLog;
use common\models\FileListNotice;
use console\models\app\OrderCert;
use wodrow\yii\rest\Controller;
use yii\base\ErrorException;
use yii\web\Response;

class BackController extends Controller
{
    /**
	 * 提交征信银行回调[工行发起专线]
	 * @desc 接受征信工行回调信息
	 * @return array $credit_info 征信信息
	 */
	public function actionGetSubmitCreditBankBack()
	{
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
//	    $data = '{"pub":{"platno":"ysxc","cmpseq":"20181101144205160041","zoneno":"3301","phybrno":"12020230","orderno":"!ysjr000000112284","assurerno":"514","cmpdate":"20181101","cmptime":"144205"},"req":{"custname":"丁彬","idno":"352224198307100015","relation":"本人","result":"001","loanCrdt":"-","cardCrdt":"-","leftNum":"-","leftAmount":"-","note":"贷款汇总(抵押):未结清贷款笔数:;未结清贷款余额:;近两年逾期次数:;单月最高逾期金额:;当前逾期金额:;近6个月平均月还:;贷款汇总(信用):未结清贷款笔数:;未结清贷款余额:;近两年逾期次数:;单月最高逾期金额:;当前逾期金额:;近6个月平均月还:;信用卡汇总:张数:;授信总额:;近6个月使用额:;近两年逾期次数:;单月最高逾期金额:;当前逾期金额:;对外担保:笔数:;余额:;备注:房贷余额:"}}';
        $data = \Yii::$app->request->post();
		if (!$data){
		    echo '{"pub":{"retcode":"20001","retmsg":"没有接收任何数据"}}';exit;
		}
		$bank_back_send_log = new BankBackSendLog();
		$bank_back_send_log->time = time();
		$reqparam = json_decode($data['reqparam']);
		$bank_back_send_log->request_route = implode('/', \Yii::$app->request->get());
		$bank_back_send_log->for_serial_number = $reqparam->pub->cmpseq;
		$bank_back_send_log->request_data = serialize($data);
		$bank_back_send_log->req_result = isset($reqparam->req->result)?$reqparam->req->result:null;
		$bank_back_send_log->req_idno = isset($reqparam->req->idno)?$reqparam->req->idno:null;
		if(!$bank_back_send_log->save()){
            echo '{"pub":{"retcode":"20002","retmsg":"'.var_export($bank_back_send_log->errors,true).var_export($bank_back_send_log->toArray(), true).'"}}';exit;
        }
		$req_data = $reqparam->req;
		if (!isset($bank_back_send_log->creditOrderLog->creditOrder)){
			$bank_back_send_log->check_error_data .= "没有记录";
			$bank_back_send_log->save();
            echo '{"pub":{"retcode":"30001","retmsg":"'.$bank_back_send_log->check_error_data.'"}}';exit;
		}
		$credit_data = $bank_back_send_log->creditOrderLog->creditOrder;
		if ($req_data->idno!=$credit_data->idno){
			$bank_back_send_log->check_error_data .= "idno验证错误";
		}
		if ($req_data->custname!=$credit_data->custname){
			$bank_back_send_log->check_error_data .= "custname验证错误";
		}
		if ($bank_back_send_log->check_error_data){
			$bank_back_send_log->save();
            echo '{"pub":{"retcode":"20003","retmsg":"'.$bank_back_send_log->check_error_data.'"}}';exit;
		}
		$trans = \Yii::$app->db->beginTransaction();
		$creditOrder= $bank_back_send_log->creditOrderLog->creditOrder;
		$creditOrder->status = $creditOrder::STATUS_HAS_GAIN;
		$creditOrder->save();
		if ($creditOrder->custom->guaranteeCompany->sign_code == 'yishang'){
		    $o_id = (int)substr($creditOrder->custom->guarantee_company_user_id, -7);
            $ct_cert = OrderCert::find()->where(['ct_status' => "ok", 'ct_code' => $creditOrder->idno, 'ct_oid' => $o_id])->one();
            if ($ct_cert){
                if ($ct_cert->ct_results == "委托中"){
                    switch ($req_data->result){
                        case '001':
                            $ct_cert->ct_results = "未查询";
                            $ct_cert->save(false);
                            break;
                        case '003':
                            $ct_cert->ct_results = "已查询";
                            $ct_cert->ct_remark = "风险预筛查不通过";
                            $ct_cert->ct_querytime = time();
                            $ct_cert->ct_query_member = 1;
                            $ct_cert->save(false);
                            $x = OrderCert::find()->where(['ct_status' => "ok", 'ct_oid' => $creditOrder->custom->guarantee_company_user_id])->andWhere(['!=', 'ct_results', '已查询'])->one();
                            if (!$x){
                                $ct_order = $ct_cert->order;
                                $ct_order->o_search_time = time();
                                $ct_order->o_status = '征信查询';
                                $ct_order->save(false);
                            }
                            break;
                        case '099':
                            $ct_cert->ct_results = "被退回";
                            $ct_cert->ct_back_reason = $req_data->note;
                            $ct_cert->save(false);
                            break;
                        default:
                            echo '{"pub":{"retcode":"40000","retmsg":"error"}}';exit;
                    }
                }
            }
        }
 		try{
 			$credit_data->serialize_data = serialize(array_merge(unserialize($credit_data->serialize_data), [
 				'result' => $req_data->result,
			    'loanCrdt' => $req_data->loanCrdt,
			    'cardCrdt' => $req_data->cardCrdt,
			    'leftNum' => $req_data->leftNum,
			    'leftAmount' => $req_data->leftAmount,
			    'note' => $req_data->note,
		    ]));
// 			$credit_data->credit_rating = $req_data->result;
//		    $credit_data->loan_overdue_record = $req_data->loanCrdt;
// 			$credit_data->credit_card_overduo_record = $req_data->cardCrdt;
// 			$credit_data->serial_card_divi_number = $req_data->leftNum;
// 			$credit_data->outstanding_balance = $req_data->leftAmount;
// 			$credit_data->note = $req_data->note;
 			$credit_data->save();
			$creditOrder->status = $creditOrder::STATUS_HAS_UPDATE;
			$creditOrder->save();
			$trans->commit();
            echo '{"pub":{"retcode":"00000","retmsg":"成功"}}';exit;
			/*return [
			    'pub' => [
			        'retcode' => '00000',
                    'retmsg' => "成功",
                ],
            ];*/
		}catch (ErrorException $e){
			$trans->rollBack();
            echo '{"pub":{"retcode":"30000","retmsg":"error"}}';exit;
		}
	}

    /**
     * 专项卡申请退回[工行发起专线]
     */
	public function actionSpecialCardBankBack()
    {
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        $data = \Yii::$app->request->post();
        $reqparam = json_decode($data['reqparam']);
        $special_card_bank_back_log = new SpecialCardBankBackLog();
        $special_card_bank_back_log->for_serial_number = $reqparam->pub->cmpseq;
        $special_card_bank_back_log->request_data = serialize($data);
        $special_card_bank_back_log->created_at = time();
        if(!$special_card_bank_back_log->save()){
            echo '{"pub":{"retcode":"20002","retmsg":"'.var_export($special_card_bank_back_log->errors,true).var_export($special_card_bank_back_log->toArray(), true).'"}}';exit;
        }
        $req_data = $reqparam->req;
        if (!isset($special_card_bank_back_log->specialCardAskLog->specialCard)){
            $special_card_bank_back_log->check_error_data .= "没有记录";
            $special_card_bank_back_log->save();
            echo '{"pub":{"retcode":"30001","retmsg":"'.$special_card_bank_back_log->check_error_data.'"}}';exit;
        }
        $car_order = $special_card_bank_back_log->specialCardAskLog->specialCard;
        /*if ($req_data->idno!=$car_order->id_no){
            $special_card_bank_back_log->check_error_data .= "id_no验证错误";
        }
        if ($req_data->custname!=$car_order->cust_name){
            $special_card_bank_back_log->check_error_data .= "cust_name验证错误";
        }*/
        if ($special_card_bank_back_log->check_error_data){
            $special_card_bank_back_log->save();
            echo '{"pub":{"retcode":"20003","retmsg":"'.$special_card_bank_back_log->check_error_data.'"}}';exit;
        }
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $car_order->serialize_data = serialize(array_merge(unserialize($car_order->serialize_data), [
                'backnote' => $req_data->backnote,
            ]));
            $car_order->save();
            $sms = new Lhwt();
            $note = "客户{$car_order->custom->master_name}线上开卡被退回，退回原因：{$req_data->backnote}";
            $com_site = $car_order->custom->creditOrderSelf->guaranteeCompanyDotSite;
            $mobiles = [$com_site->contact_mobile];
            if ($com_site->sign_code == 'yishang_dot_site_new_1'){
                $mobiles = ['17767154587', '18657180077', '15067128046'];
            }
            $statusCode = $sms->sendSms($mobiles, $note);
            $trans->commit();
            echo '{"pub":{"retcode":"00000","retmsg":"ok"}}';exit;
        }catch (ErrorException $e){
            $trans->rollBack();
            echo '{"pub":{"retcode":"30000","retmsg":"error"}}';exit;
        }
    }

    /**
     * 申请退回接口(一手车，二手车)[工行专线]
     */
    public function actionApplyBack()
    {
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        $data = \Yii::$app->request->bodyParams;
        $reqparam = json_decode($data['reqparam']);
        $sms = new Lhwt();
        $car_order_bank_back_log = new CarOrderBankBackLog();
        $car_order_bank_back_log->for_serial_number = $reqparam->pub->cmpseq;
        $car_order_bank_back_log->request_data = serialize($data);
        $car_order_bank_back_log->created_at = time();
        if(!$car_order_bank_back_log->save()){
            echo '{"pub":{"retcode":"20002","retmsg":"'.var_export($car_order_bank_back_log->errors,true).var_export($car_order_bank_back_log->toArray(), true).'"}}';exit;
        }
        $req_data = $reqparam->req;
        if (!isset($car_order_bank_back_log->carOrderLog->carOrder)){
            $car_order_bank_back_log->check_error_data .= "没有记录";
            $car_order_bank_back_log->save();
            echo '{"pub":{"retcode":"30001","retmsg":"'.$car_order_bank_back_log->check_error_data.'"}}';exit;
        }
        $car_order = $car_order_bank_back_log->carOrderLog->carOrder;
        $custom = $car_order->custom;
        $bank = $custom->creditOrderSelf->bank;
        $company_site = $custom->creditOrderSelf->guaranteeCompanyDotSite;
        /*if ($req_data->idno!=$car_order->id_no){
            $car_order_bank_back_log->check_error_data .= "id_no验证错误";
        }
        if ($req_data->custname!=$car_order->cust_name){
            $car_order_bank_back_log->check_error_data .= "cust_name验证错误";
        }*/
        if ($car_order_bank_back_log->check_error_data){
            $car_order_bank_back_log->save();
            echo '{"pub":{"retcode":"20003","retmsg":"'.$car_order_bank_back_log->check_error_data.'"}}';exit;
        }
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $car_order->serialize_data = serialize(array_merge(unserialize($car_order->serialize_data), [
                'backnote' => $req_data->backnote,
            ]));
            $car_order->save();
            $trans->commit();
            $note = "{$bank->name} {$custom->creditOrderSelf->custname} {$custom->creditOrderSelf->idno} {$custom->orderno} {$req_data->backnote}";
            if ($req_data->backnote != "已放款"){
                $statusCode = $sms->sendSms([$company_site->contact_mobile], $note);
            }
            echo '{"pub":{"retcode":"00000","retmsg":"ok"}}';exit;
        }catch (ErrorException $e){
            $trans->rollBack();
            echo '{"pub":{"retcode":"30000","retmsg":"error"}}';exit;
        }
    }

    /**
     * 手工获取图片[工行专线]
     * @desc 手工获取图片
     * @param json $reqparam
     */
    public function actionGetManualPics($reqparam)
    {
//        \Yii::$app->response->format = Response::FORMAT_JSON;
        $log = new ManualPicsGetLog();
        $log->created_at = time();
        $log->req_data = $reqparam;
        $log->save();
        $reqparam = json_decode($reqparam);
        $pub = $reqparam->pub;
        $req = $reqparam->req;
        $picid = $req->picid;
        $log->picid = $picid;
        $log->save();
        if (!$orderno = $pub->orderno){
            $resp = [
                'pub' => [
                    'retcode' => "30003",
                    'retmsg' => "error:没有找到orderno",
                ],
            ];
            $resp = json_encode($resp, JSON_UNESCAPED_UNICODE);
            $log->resp_data = $resp;
            $log->error_msg = "error:没有找到orderno";
            $log->save();
            echo $resp;
            exit;
        }
        $custom = Custom::findOne(['orderno'=>$orderno]);
        if (!$custom){
            $resp = [
                'pub' => [
                    'retcode' => "30004",
                    'retmsg' => "error:没有找到custom",
                ],
            ];
            $resp = json_encode($resp, JSON_UNESCAPED_UNICODE);
            $log->resp_data = $resp;
            $log->error_msg = "error:没有找到custom";
            $log->save();
            echo $resp;
            exit;
        }
        $log->custom_id = $custom->id;
        $log->save();
        $pics = ManualPics::find()->select(['picurl', 'picnote'])->where(['custom_id'=>$custom->id])->andWhere(['picid'=>$picid])->asArray()->all();
        $r = [
            'pub' => [
                'retcode' => "00000",
                'retmsg' => "获取成功",
            ],
            'ans' => [
                'picnum' => count($pics),
                'pics' => $pics,
            ],
        ];
        $resp = json_encode($r, JSON_UNESCAPED_UNICODE);
        $log->resp_data = $resp;
        $log->save();
        echo $resp;
        exit;
    }

    /**
     * 下载回调的资源[工行专线]
     * @desc 接受征信工行回调信息
     * @return array $credit_info 征信信息
     */
    public function actionGetPic($imageName)
    {
        $multi_media = MultiMedia::find()->where(['like', 'picurl', '%'.$imageName, false])->one();
        if ($multi_media){
            $multi_media->last_visit_at = time();
            $multi_media->last_visit_ip = \Yii::$app->request->userIP;
            $multi_media->save();
        }
        $imageName = str_replace('_', '/', $imageName);
        $path = \Yii::getAlias('@wroot').$imageName;
//        $url= \Yii::$app->params['api_domain'].\Yii::getAlias('@web').$imageName;
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($path));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }

    /**
     * 文件清单生成通知[工行专线]
     */
    public function actionFileListNotice(){
//        \Yii::$app->trigger(\Yii::$app::EVENT_AFTER_ACTION);
        $data = \Yii::$app->request->post();
        $reqparam = json_decode($data['reqparam']);
        $file_list_notice = new FileListNotice();
        $file_list_notice->assurerno = $reqparam->pub->assurerno;
        $file_list_notice->filetype = $reqparam->req->filetype;
        $file_list_notice->filesrc = $reqparam->req->filesrc;
        $file_list_notice->datadt = $reqparam->req->datadt;
        $trans = \Yii::$app->db->beginTransaction();
        try{
            $file_list_notice->save(false);
            $trans->commit();
            echo '{"pub":{"retcode":"00000","retmsg":"成功"}}';exit;
        }catch (ErrorException $e){
            $trans->rollBack();
            echo '{"pub":{"retcode":"30000","retmsg":"error"}}';exit;
        }
    }
}